package com.tongcao.cn.mq.handle;

import com.tongcao.cn.mq.ConsumerCallBack;
import com.tongcao.cn.mq.anntation.MessageTag;
import com.tongcao.cn.mq.to.AsyncMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author:tongcao
 * @Date:2019/1/25 16:42
 * Description:
 */
public class BookerMessageHandle extends MessageHandle {


    private Logger log = LoggerFactory.getLogger(BookerMessageHandle.class);

    private Map<String, ConsumerCallBack> callBackMap = new ConcurrentHashMap<>();

    private String tagSplit = "||";

    /**
     * @param asyncMsg
     * @return
     */
    @Override
    public boolean consume(AsyncMsg asyncMsg) {
        boolean result = true;

        try {
            ConsumerCallBack consume = callBackMap.get(asyncMsg.getTag());
            if (consume == null) {
                return result;
            }
            result = consume.process(asyncMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 配置多tag对应的消息处理类
     *
     * @param callBackList
     */
    public void setCallBackList(List<ConsumerCallBack> callBackList) {
        if (CollectionUtils.isEmpty(callBackList)) {
            return;
        }

        StringBuffer sb = new StringBuffer();
        for (ConsumerCallBack consume : callBackList) {
            if (consume == null) {
                continue;
            }

            Class<?> clazz = consume.getClass();
            if (isProxyBean(clazz)) {
                clazz = AopUtils.getTargetClass(consume);
            }

            MessageTag messageTag = clazz.getAnnotation(MessageTag.class);
            if (messageTag == null) {
                log.error("配置ConsumeCallback的messageTag为空,请检查后配置:" + consume);
            }
            String[] tags = messageTag.tag();
            for (String tag : tags) {
                callBackMap.put(tag, consume);
                sb.append(tag).append(tagSplit);
            }
            String str = sb.toString();
            if (str.endsWith(tagSplit)) {
                str = sb.substring(0, sb.length() - tagSplit.length());
            }
            log.debug("已订阅:[" + str + "]这些类型的消息");
            setSubExpression(str);
        }
    }

    private boolean isProxyBean(Object bean) {
        return AopUtils.isAopProxy(bean);
    }
}
